package com.cn.jx.configuration;

import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jx.base.SessionUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;

import com.cn.jx.manager.po.User;
import com.cn.jx.manager.service.query.IUserServiceQry;
import com.jx.util.Constant;
import com.jx.util.Utility;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since 
 * <p>创建时间：2019年12月1日
 * <p>功能描述：拦截登录
 * <p>官方网站：management/admin/index
 * <p>邮箱地址：524577360@qq.com
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 定义{@link IUserService userService <tt>用户操作接口</tt>}
	 */
	@Autowired
	private IUserServiceQry userServiceQry;
	
	
	/**
	 * 拦截执行之前操作
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getContextPath();
		String scheme = request.getScheme();
		String serverName = request.getServerName();
		int port = request.getServerPort();
		String basePath = scheme + "://" + serverName + ":" + port + path;

		// 先获取session登录对象
		Object obj = request.getSession().getAttribute(Constant.SESSION_ADMIN_KEY);

		// 如果为空 则去cookie 取记录的用户名密码 然后去redis获取。
		if (obj == null) {// 重新登录session空
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				if (Constant.COOKIE_ADMIN_KEY.equals(cookie.getName())) {
					// 存在cookie
					String cvalue = URLDecoder.decode(cookie.getValue(), "UTF-8");
					// 获取session登录信息
					obj = redisUtil.hget("LoginController", "doLoginAdmin[" + cvalue + "]");
					if (obj != null) {
						// 缓存中获取到设置到session中
						Object objUser = JSONObject.parse(obj.toString());
						SessionUser sUser = (SessionUser) objUser;
						request.getSession().setAttribute(Constant.SESSION_ADMIN_KEY, sUser);
					}
				}
			}
		}

		if (obj == null) {
			response.sendRedirect(basePath + "/login/page");
			return false;
		}

		boolean tologin = false;
		SessionUser sessUser = (SessionUser) obj;
		String loginname = sessUser.getLoginName();
		if (!Utility.getSuperName().equals(loginname)) {// 登录名为超级名
			if ("E000".equals(sessUser.getEmployeeCode())) {
				// 超级管理员登录超时 从新登录
				tologin = true;
			} else {
				// 去数据库查询用户是否存在
				User user = userServiceQry.findUserByLoginName(loginname);
				if (user == null) {
					// 不存在
					tologin = true;
				}
			}
		}
		if (tologin) {
			// 清理session redis 跳转登录
			request.getSession().removeAttribute(Constant.SESSION_ADMIN_KEY);// 移除session
			redisUtil.hdelItem("LoginController", "doLoginAdmin[" + loginname + "]");
			response.sendRedirect(basePath + "/login/page");
			return false;
		}
		
		return true;
	}
	
}
